package com.patrrr.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xmlpull.v1.XmlSerializer;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.os.Environment;
import android.util.Xml;

import com.patrrr.Note.FolderBean;
import com.patrrr.Note.NoteBean;
import com.patrrr.Note.NoteList;
import com.patrrr.SQLite3.DBHandler;
import com.patrrr.SQLite3.DBHelper;

public class Backuper {
	private Context mContext;
	private File sd;

	private static final String XIAOMI_NOTE = "pXiaomi_note.xml";

	private static final String NOTES = "notes";

	private static final String FOLDER = "folder";
	private static final String NOTE = "note";

	private static final String _ID = DBHelper.ID;

	private static final String FOLDER_NAME = DBHelper.FOLDER_NAME;

	private static final String FOLDER_ID = DBHelper.NOTE_FOLDERID;
	private static final String CONTENT = DBHelper.NOTE_CONTENT;
	private static final String CREATETIME = DBHelper.NOTE_CREATETIME;
	private static final String ALERTTIME = DBHelper.NOTE_ALERTTIME;
	private static final String COLOR = DBHelper.NOTE_COLOR;
	private static final String WIDGETID = DBHelper.NOTE_WIDGETID;

	public Backuper(Context context) {
		mContext = context;
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			sd = Environment.getExternalStorageDirectory();
		}
	}

	public void backup() {
		DBHandler dbHandler = new DBHandler(mContext);
		Cursor folder_cursor = dbHandler.query(DBHelper.FOLDER);
		Cursor note_cursor = dbHandler.query(DBHelper.NOTE);

		XmlSerializer serializer = Xml.newSerializer();

		File folderFile = new File(sd, XIAOMI_NOTE);
		try {
			FileOutputStream fileOutputStream = new FileOutputStream(
					folderFile, false);
			serializer.setOutput(fileOutputStream, "UTF-8");

			serializer.startDocument("UTF-8", true);
			serializer.startTag("", NOTES);
			while (folder_cursor.moveToNext()) {
				serializer.startTag("", FOLDER);

				serializer.startTag("", _ID);
				serializer.text(""
						+ folder_cursor.getInt(folder_cursor
								.getColumnIndexOrThrow(DBHelper.ID)));
				serializer.endTag("", _ID);

				serializer.startTag("", FOLDER_NAME);
				serializer.text(folder_cursor.getString(folder_cursor
						.getColumnIndexOrThrow(DBHelper.FOLDER_NAME)));
				serializer.endTag("", FOLDER_NAME);

				serializer.endTag("", FOLDER);
			}
			while (note_cursor.moveToNext()) {
				serializer.startTag("", NOTE);

				serializer.startTag("", _ID);
				serializer.text(""
						+ note_cursor.getInt(note_cursor
								.getColumnIndexOrThrow(DBHelper.ID)));
				serializer.endTag("", _ID);

				serializer.startTag("", FOLDER_ID);
				serializer
						.text(""
								+ note_cursor
										.getInt(note_cursor
												.getColumnIndexOrThrow(DBHelper.NOTE_FOLDERID)));
				serializer.endTag("", FOLDER_ID);

				serializer.startTag("", CONTENT);
				serializer.text(note_cursor.getString(note_cursor
						.getColumnIndexOrThrow(DBHelper.NOTE_CONTENT)));
				serializer.endTag("", CONTENT);

				serializer.startTag("", CREATETIME);
				serializer
						.text(""
								+ note_cursor
										.getLong(note_cursor
												.getColumnIndexOrThrow(DBHelper.NOTE_CREATETIME)));
				serializer.endTag("", CREATETIME);

				serializer.startTag("", ALERTTIME);
				serializer
						.text(""
								+ note_cursor
										.getLong(note_cursor
												.getColumnIndexOrThrow(DBHelper.NOTE_ALERTTIME)));
				serializer.endTag("", ALERTTIME);

				serializer.startTag("", COLOR);
				serializer.text(""
						+ note_cursor.getInt(note_cursor
								.getColumnIndexOrThrow(DBHelper.NOTE_COLOR)));
				serializer.endTag("", COLOR);

				serializer.startTag("", WIDGETID);
				serializer
						.text(""
								+ note_cursor
										.getInt(note_cursor
												.getColumnIndexOrThrow(DBHelper.NOTE_WIDGETID)));
				serializer.endTag("", WIDGETID);

				serializer.endTag("", NOTE);
			}
			serializer.endTag("", NOTES);
			serializer.endDocument();

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log(e.toString());
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log(e.toString());
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log(e.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log(e.toString());
		}
		dbHandler.close();
		folder_cursor.close();
		note_cursor.close();
	}

	public void export() {
		DBHandler dbHandler = new DBHandler(mContext);
		Cursor cursor = dbHandler.query(DBHelper.NOTE);
		SimpleDateFormat dateFormat = new SimpleDateFormat("MMdd_hhmm");
		String name = "note_"
				+ dateFormat.format(Calendar.getInstance().getTime()) + ".txt";

		SimpleDateFormat dateFormat2 = new SimpleDateFormat("MM-dd hh:mm");
		File file = new File(sd, name);
		try {
			FileWriter writer = new FileWriter(file);
			BufferedWriter bufferedWriter = new BufferedWriter(writer);
			ArrayList<FolderBean> folderList = dbHandler.getFolderList();
			ArrayList<NoteBean> defaultList = dbHandler
					.getNoteInFolder(NoteList.DEFAULTFOLDER_ID);
			bufferedWriter.append("小米便签---" + "本次共输出：" + folderList.size()
					+ "条目录 " + cursor.getCount() + "条便签---"
					+ dateFormat2.format(new Date()));
			bufferedWriter.append("\n\n\n");
			if (defaultList.size() != 0) {
				bufferedWriter.append("\n------------\n");
				bufferedWriter.append("我的便签");
				bufferedWriter.append("\n------------\n");
			}
			for (int i = 0; i < defaultList.size(); i++) {
				NoteBean noteBean = defaultList.get(i);
				bufferedWriter.append(dateFormat2.format(new Date(noteBean
						.getCreateTime())));
				bufferedWriter.append("\n");
				bufferedWriter.append(noteBean.getContent());
				bufferedWriter.append("\n\n\n");
			}
			for (int i = 0; i < folderList.size(); i++) {
				ArrayList<NoteBean> noteList = dbHandler
						.getNoteInFolder(folderList.get(i).getId());
				bufferedWriter.append("\n------------\n");
				bufferedWriter.append(folderList.get(i).getFolderName());
				bufferedWriter.append("\n------------\n");
				for (int j = 0; j < noteList.size(); j++) {
					NoteBean noteBean = noteList.get(j);
					bufferedWriter.append(dateFormat2.format(new Date(noteBean
							.getCreateTime())));
					bufferedWriter.append("\n");
					bufferedWriter.append(noteBean.getContent());
					bufferedWriter.append("\n\n\n");
				}
			}
			bufferedWriter.flush();
			writer.flush();
			bufferedWriter.close();
			writer.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log(e.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log(e.toString());
		} finally {

		}
		cursor.close();
		dbHandler.close();
	}

	public void restore() {		
		DBHandler dbHandler = new DBHandler(mContext);
		SAXParserFactory factory = SAXParserFactory.newInstance();
		try {
			SAXParser parser = factory.newSAXParser();
			XMLReader reader = parser.getXMLReader();

			NoteParse noteParse = new NoteParse();
			reader.setContentHandler(noteParse);
			File file=new File(sd, XIAOMI_NOTE);
			FileInputStream inputStream = new FileInputStream(file);
			InputSource inputSource = new InputSource(inputStream);
			reader.parse(inputSource);
			ArrayList<NoteBean> noteBeans = noteParse.getNotes();
			ArrayList<FolderBean> folderBeans = noteParse.getFolders();
			for (int i = 0; i < noteBeans.size(); i++) {
				NoteBean noteBean = noteBeans.get(i);
				ContentValues values = new ContentValues();
				values.put(DBHelper.ID, noteBean.getId());
				values.put(DBHelper.NOTE_FOLDERID, noteBean.getFolderId());
				values.put(DBHelper.NOTE_CONTENT, noteBean.getContent());
				values.put(DBHelper.NOTE_CREATETIME, noteBean.getCreateTime());
				values.put(DBHelper.NOTE_ALERTTIME, noteBean.getAlertTime());
				values.put(DBHelper.NOTE_COLOR, noteBean.getColor());
				values.put(DBHelper.NOTE_WIDGETID, noteBean.getWidgetId());
				//dbHandler.insert(DBHelper.NOTE, values);
			}
			for (int i = 0; i < folderBeans.size(); i++) {
				FolderBean folderBean = folderBeans.get(i);
				ContentValues values = new ContentValues();
				values.put(DBHelper.ID, folderBean.getId());
				values.put(DBHelper.FOLDER_NAME, folderBean.getFolderName());
				//dbHandler.insert(DBHelper.FOLDER, values);
			}
			dbHandler.close();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println(e.toString());
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println(e.toString());
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println(e.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println(e.toString());
			e.printStackTrace();
		}
	}

	public static void Log(String str) {
		System.out.println(str);
	}

}
